<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { showToast } from 'vant';

// 商品接口定义
interface Product {
  id: number;
  name: string;
  price: number;
  image: string;
  description?: string;
  originalPrice?: number;
  tag?: string;
}

// 购物车商品接口定义
interface CartItem {
  id: number;
  name: string;
  price: number;
  image: string;
  quantity: number;
  selected: boolean;
  color: string;
  size: string;
}

const route = useRoute();
const router = useRouter();
const productId = route.params.id;

// 商品数据
const product = ref<Product | null>(null);
const loading = ref(true);
const error = ref(false);

// 选择的颜色和规格
const selectedColor = ref('');
const selectedSize = ref('');

// 购买数量
const quantity = ref(1);

// 颜色选项
const colorOptions = ref([
  { name: '经典黑', value: 'black' },
  { name: '冰川灰', value: 'gray' }
]);

// 规格选项
const sizeOptions = ref([
  { name: '单槽', value: 'single' }
]);

// 返回上一页
const goBack = () => {
  router.back();
};

// 获取商品详情
const fetchProductDetail = async () => {
  loading.value = true;
  error.value = false;
  
  try {
    const response = await axios.get(`http://localhost:3000/shop/product/${productId}`);
    if (response.data.code === 200) {
      product.value = response.data.data;
      // 默认选中第一个颜色和规格
      if (colorOptions.value.length > 0) {
        selectedColor.value = colorOptions.value[0].value;
      }
      if (sizeOptions.value.length > 0) {
        selectedSize.value = sizeOptions.value[0].value;
      }
    } else {
      throw new Error(response.data.msg);
    }
  } catch (err) {
    console.error('获取商品详情失败:', err);
    error.value = true;
    showToast('获取商品详情失败');
  } finally {
    loading.value = false;
  }
};

// 增加数量
const increaseQuantity = () => {
  quantity.value++;
};

// 减少数量
const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--;
  }
};

// 选择颜色
const selectColor = (color: string) => {
  selectedColor.value = color;
};

// 选择规格
const selectSize = (size: string) => {
  selectedSize.value = size;
};

// 加入购物车
const addToCart = () => {
  if (!selectedColor.value || !selectedSize.value) {
    showToast('请选择颜色和规格');
    return;
  }
  
  if (!product.value) {
    showToast('商品信息加载中，请稍后重试');
    return;
  }
  
  // 获取当前购物车数据
  const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]');
  
  // 检查是否已存在相同商品（包括颜色和规格）
  const existingItemIndex = cartItems.findIndex(item => 
    item.id === product.value!.id && 
    item.color === selectedColor.value && 
    item.size === selectedSize.value
  );
  
  if (existingItemIndex > -1) {
    // 如果已存在，增加数量
    cartItems[existingItemIndex].quantity += quantity.value;
  } else {
    // 如果不存在，添加新商品
    const newItem: CartItem = {
      id: product.value.id,
      name: product.value.name,
      price: product.value.price,
      image: product.value.image,
      quantity: quantity.value,
      selected: true,
      color: selectedColor.value,
      size: selectedSize.value
    };
    cartItems.push(newItem);
  }
  
  // 保存到本地存储
  localStorage.setItem('cartItems', JSON.stringify(cartItems));
  
  // 显示成功提示
  showToast(`已加入购物车 (${quantity.value}件)`);
};

onMounted(() => {
  fetchProductDetail();
});
</script>

<template>
  <div class="product-detail">
    <!-- 顶部导航栏 -->
    <div class="nav-bar">
      <div class="back-button" @click="goBack">
        <i class="back-icon">←</i>
      </div>
      <div class="title">商品详情</div>
      <div class="placeholder"></div>
    </div>
    
    <van-loading v-if="loading" class="loading" type="spinner" size="24px" />
    
    <div v-else-if="error" class="error-message">
      加载失败，请重试
    </div>
    
    <div v-else-if="product" class="product-content">
      <!-- 商品图片 -->
      <div class="product-image">
        <img :src="product.image" :alt="product.name" />
      </div>
      
      <!-- 商品信息 -->
      <div class="product-info">
        <div class="product-price">
          <span class="current-price">¥{{ product.price }}</span>
          <span v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</span>
        </div>
        
        <div class="product-name">{{ product.name }}</div>
        
        <div class="product-desc" v-if="product.description">
          {{ product.description }}
        </div>
        
        <div class="product-tag" v-if="product.tag">
          <van-tag type="danger">{{ product.tag }}</van-tag>
        </div>
      </div>
      
      <!-- 选择颜色 -->
      <div class="select-section">
        <div class="section-title">选择颜色</div>
        <div class="option-list">
          <div 
            v-for="color in colorOptions" 
            :key="color.value"
            class="option-item" 
            :class="{ active: selectedColor === color.value }"
            @click="selectColor(color.value)"
          >
            {{ color.name }}
          </div>
        </div>
      </div>
      
      <!-- 选择规格 -->
      <div class="select-section">
        <div class="section-title">选择规格</div>
        <div class="option-list">
          <div 
            v-for="size in sizeOptions" 
            :key="size.value"
            class="option-item" 
            :class="{ active: selectedSize === size.value }"
            @click="selectSize(size.value)"
          >
            {{ size.name }}
          </div>
        </div>
      </div>
      
      <!-- 购买数量 -->
      <div class="select-section">
        <div class="section-title">购买数量</div>
        <div class="quantity-selector">
          <div class="quantity-button minus" @click="decreaseQuantity">-</div>
          <div class="quantity-value">{{ quantity }}</div>
          <div class="quantity-button plus" @click="increaseQuantity">+</div>
        </div>
      </div>
    </div>
    
    <!-- 底部操作栏 -->
    <div class="bottom-bar">
      <div class="cart-button" @click="addToCart">加入购物车</div>
    </div>
  </div>
</template>

<style scoped>
.product-detail {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f7f8fa;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #ffffff;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.back-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  cursor: pointer;
}

.back-icon {
  font-style: normal;
  font-weight: bold;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.placeholder {
  width: 30px;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.error-message {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #ff5252;
}

.product-content {
  flex: 1;
  padding-bottom: 60px;
}

.product-image {
  width: 100%;
  height: 300px;
  background-color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  background-color: #ffffff;
  padding: 16px;
  margin-bottom: 12px;
}

.product-price {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.current-price {
  font-size: 24px;
  font-weight: bold;
  color: #ff5252;
  margin-right: 8px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.product-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.product-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.product-tag {
  margin-top: 8px;
}

.select-section {
  background-color: #ffffff;
  padding: 16px;
  margin-bottom: 12px;
}

.section-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.option-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.option-item {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  cursor: pointer;
}

.option-item.active {
  border-color: #42b983;
  background-color: #e6f7f0;
  color: #42b983;
}

.quantity-selector {
  display: flex;
  align-items: center;
}

.quantity-button {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ddd;
  cursor: pointer;
}

.quantity-value {
  width: 50px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  height: 50px;
  background-color: #ffffff;
  box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.1);
}

.cart-button {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #42b983;
  color: #ffffff;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
}
</style>

// 合并选择状态管理（替换原有的多个选择相关变量和函数）
const selectionState = reactive({
  color: '',
  size: '',
  quantity: 1,
  
  get isValid() {
    return this.color && this.size && product.value
  },
  
  reset() {
    this.quantity = 1
  },
  
  adjustQuantity(delta: number) {
    this.quantity = Math.max(1, this.quantity + delta)
  }
})

// 简化购物车操作（替换原有的购物车相关函数）
const cartOperations = {
  get items() {
    return JSON.parse(localStorage.getItem('cartItems') || '[]')
  },
  
  save(items: CartItem[]) {
    localStorage.setItem('cartItems', JSON.stringify(items))
  },
  
  addItem() {
    if (!selectionState.isValid) {
      showToast('请选择颜色和规格')
      return
    }
    
    const items = this.items
    const existingIndex = items.findIndex(item => 
      item.id === product.value!.id && 
      item.color === selectionState.color && 
      item.size === selectionState.size
    )
    
    if (existingIndex > -1) {
      items[existingIndex].quantity += selectionState.quantity
    } else {
      items.push({
        id: product.value!.id,
        name: product.value!.name,
        price: product.value!.price,
        image: product.value!.image,
        quantity: selectionState.quantity,
        selected: true,
        color: selectionState.color,
        size: selectionState.size
      })
    }
    
    this.save(items)
    showToast(`已加入购物车 (${selectionState.quantity}件)`)
  }
}

// 更新函数调用
const selectColor = (color: string) => { selectionState.color = color }
const selectSize = (size: string) => { selectionState.size = size }
const increaseQuantity = () => selectionState.adjustQuantity(1)
const decreaseQuantity = () => selectionState.adjustQuantity(-1)
const addToCart = () => cartOperations.addItem()